<template>
  <div class="dept-container">    
    <!-- Search row with improved layout -->
    <div class="search-row">
      <span class="search-label">部门名称：</span>
      <el-input v-model="dept_name" size="small" class="search-input" />
      <span class="search-label">负责人：</span>
      <el-input v-model="leader" size="small" class="search-input" />
      <el-button type="primary" size="small" @click="query">查询</el-button>
      <el-button size="small" @click="reset">重置</el-button>
      <div class="flex-grow"></div>
      <el-button type="primary" size="small" @click="addEdit">添加</el-button>
    </div>

    <el-divider style="margin: 10px 0" />

    <!-- Table container with original layout -->
    <div class="table-container">
      <el-table 
        :data="tableData" 
        stripe 
        border 
        style="width: 100%"
        :cell-style="{ textAlign: 'center' }"
        :header-cell-style="{
          textAlign: 'center',
          background: '#f5f7fa',
          fontWeight: 'bold'
        }"
      >
        <el-table-column prop="dept_name" label="部门名称" />
        <el-table-column prop="parent_id" label="上级部门">
          <template #default="scope">
            {{ ParentId(scope.row.parent_id) }}
          </template>
        </el-table-column>
        <el-table-column prop="leader" label="负责人" />
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            {{ scope.row.status == 0 ? "正常" : "停用" }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row.dept_id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- Pagination -->
      <div class="pagination-wrapper">
        <el-pagination 
          v-model:current-page="currentPage" 
          v-model:page-size="pageSize" 
          :page-sizes="[5, 10, 20, 50]"
          :background="true" 
          layout="total, sizes, prev, pager, next, jumper" 
          :total="pageCount"
          @size-change="handleSizeChange" 
          @current-change="handleCurrentChange" size="small"
        />
      </div>
    </div>

    <!-- Delete Confirmation Dialog -->
    <el-dialog v-model="dialogVisible1" title="删除部门信息" width="500px">
      <span>确定删除该条部门信息吗？</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="close1">取消</el-button>
          <el-button type="primary" @click="del">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- Department Form Drawer -->
    <el-drawer 
      v-model="dialogVisible" 
      :title="title" 
      :direction="direction" 
      size="30%"
      @close="close"
    >
      <el-form 
        ref="ruleFormRef" 
        :model="dept" 
        :rules="rules"
        label-width="80px"
        class="compact-form"
      >
        <el-form-item prop="dept_name" label="部门名称">
          <el-input v-model="dept.dept_name" placeholder="部门名称" />
        </el-form-item>
        
        <el-form-item label="上级部门">
          <el-select v-model="dept.parent_id" placeholder="上级部门">
            <el-option 
              v-for="item in options" 
              :key="item.dept_id" 
              :label="item.dept_name"
              :value="item.dept_id" 
            />
          </el-select>
        </el-form-item>
        
        <el-form-item prop="leader" label="负责人">
          <el-input v-model="dept.leader" placeholder="负责人" />
        </el-form-item>
        
        <el-form-item prop="phone" label="电话">
          <el-input v-model="dept.phone" placeholder="电话" />
        </el-form-item>
        
        <el-form-item label="状态">
          <el-radio-group v-model="dept.status">
            <el-radio value="0">正常</el-radio>
            <el-radio value="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="close">取消</el-button>
          <el-button type="primary" @click="deptAdd">确定</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'

export default {
  setup() {
    const tableData = ref([])
    const dept_name = ref("")
    const leader = ref("")
    const currentPage = ref(1)
    const pageSize = ref(10)
    const pageCount = ref(0)
    const options = ref([])
    const dialogVisible = ref(false)
    const dialogVisible1 = ref(false)
    const dept_id = ref(0)
    const title = ref("添加部门信息")
    const direction = ref('rtl')
    
    const dept = reactive({
      dept_id: "0",
      parent_id: "0",
      dept_name: "",
      leader: "",
      phone: "",
      status: "0",
      create_by: localStorage.getItem('userLName'),
      create_time: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ')
    })

    const rules = reactive({
      dept_name: [
        { required: true, message: "部门名称不能为空", trigger: ["blur","change"] }
      ],
      leader: [
        { required: true, message: "负责人不能为空", trigger: ["blur","change"] }
      ],
      phone: [
        { required: true, message: "电话不能为空", trigger: ["blur","change"] }
      ]
    })

    onMounted(() => {
      deptOpt()
      fill()
      count()
    })

    function fill() {
      axios.get("http://localhost:5181/api/Dept/GetDepts", {
        params: {
          dept_name: dept_name.value,
          leader: leader.value,
          currentPage: currentPage.value,
          pageSize: pageSize.value
        },
        headers: {
          authorization: `Bearer ${localStorage.getItem('token')}`
        }
      }).then((result) => {
        tableData.value = result.data
      }).catch((err) => {
        console.error(err)
      })
    }

    function count() {
      axios.get("http://localhost:5181/api/Dept/GetDeptsCount", {
        params: {
          dept_name: dept_name.value,
          leader: leader.value
        },
        headers: {
          authorization: `Bearer ${localStorage.getItem('token')}`
        }
      }).then((result) => {
        pageCount.value = result.data
      }).catch((err) => {
        console.error(err)
      })
    }

    function deptOpt() {
      axios.get("http://localhost:5181/api/Dept/DeptOpt", {
        headers: {
          authorization: `Bearer ${localStorage.getItem('token')}`
        }
      }).then((result) => {
        options.value = [
          { dept_id: '0', dept_name: '请选择部门' },
          ...result.data
        ]
      }).catch((err) => {
        console.error(err)
      })
    }

    function ParentId(row) {
      if (!row || row === '0') return "无"
      const parentDept = options.value.find((dept) => dept.dept_id === row)
      return parentDept ? parentDept.dept_name : "未知部门"
    }

    function query() {
      fill()
      count()
    }

    function reset() {
      dept_name.value = ""
      leader.value = ""
      query()
    }

    function handleSizeChange(val) {
      pageSize.value = val
      fill()
    }

    function handleCurrentChange(val) {
      currentPage.value = val
      fill()
    }

    function addEdit() {
      title.value = "添加部门信息"
      dialogVisible.value = true
    }

    function handleEdit(row) {
      title.value = "修改部门信息"
      Object.assign(dept, row)
      if (dept.parent_id == 0) {
        dept.parent_id = '0'
      }
      dialogVisible.value = true
    }

    function handleDelete(id) {
      dept_id.value = id
      dialogVisible1.value = true
    }

    function del() {
      axios.put("http://localhost:5181/api/Dept/DeptDelete", {
        dept_id: dept_id.value,
        del_flag: '1'
      }, {
        headers: {
          authorization: `Bearer ${localStorage.getItem('token')}`
        }
      }).then((result) => {
        if (result.data > 0) {
          ElMessage.success('删除成功')
          fill()
          count()
          close1()
        }
      }).catch((err) => {
        console.error(err)
      })
    }

    function deptAdd() {
      if (dept.dept_id === "0") {
        axios.post("http://localhost:5181/api/Dept/DeptAdd", {
          ...dept,
          del_flag: "0"
        }, {
          headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
          }
        }).then((result) => {
          if (result.data > 0) {
            ElMessage.success('添加成功')
            fill()
            count()
            close()
          }
        }).catch((err) => {
          console.error(err)
        })
      } else {
        axios.put("http://localhost:5181/api/Dept/DeptUpdate", {
          ...dept,
          update_by: localStorage.getItem('userLName'),
          update_time: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ')
        }, {
          headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
          }
        }).then((result) => {
          if (result.data > 0) {
            ElMessage.success('修改成功')
            fill()
            count()
            close()
          }
        }).catch((err) => {
          console.error(err)
        })
      }
    }

    function close() {
      dialogVisible.value = false
      dept.dept_id = "0"
      dept.parent_id = "0"
      dept.dept_name = ""
      dept.leader = ""
      dept.phone = ""
      dept.status = "0"
    }

    function close1() {
      dialogVisible1.value = false
      dept_id.value = 0
    }

    return {
      tableData, dept_name, leader, currentPage, pageSize, pageCount,
      dialogVisible, dialogVisible1, dept_id, title, direction, dept, rules,
      options, query, reset, handleSizeChange, handleCurrentChange, ParentId,
      addEdit, handleEdit, handleDelete, del, deptAdd, close, close1
    }
  }
}
</script>

<style scoped>
.dept-container {
  padding: 10px;
}


.search-row {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: -3px;
  margin-top: -40px;
}

.search-label {
  white-space: nowrap;
  font-size: 13px;
}

.search-input {
  width: 200px;
}

.flex-grow {
  flex-grow: 1;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 15px;
}

.compact-form {
  padding: 20px;
}

.dialog-footer {
  text-align: center;
}

/* Original table styling */
:deep(.el-table) {
  border: 1px solid #ebeef5;
}

:deep(.el-table__header) {
  background-color: #f5f7fa;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  font-weight: bold;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: #fafafa;
}

:deep(.el-table--border) {
  border: 1px solid #ebeef5;
  border-right: none;
  border-bottom: none;
}

:deep(.el-table--border td, .el-table--border th) {
  border-right: 1px solid #ebeef5;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-table--border::after, .el-table--group::after) {
  background-color: #ebeef5;
}

:deep(.el-table--border .el-table__cell) {
  border-right: 1px solid #ebeef5;
}

:deep(.el-table__row) {
  height: 36px !important;
}

:deep(.el-table th.el-table__cell) {
  height: 36px !important;
}

:deep(.el-button--small) {
  padding: 5px 8px;
  height: 24px;
}
</style>